<?php
namespace Core\Service;

use Core\Application;
use Phalcon\Di\Injectable;
use Phalcon\Mvc\Router\Annotations as RouterAnnotations;

class Router extends Injectable {

    public function register() {
        $router = new RouterAnnotations(true);
        $router->setDefaultModule(Application::SYSTEM_DEFAULT_MODULE);
        $router->setDefaultNamespace(Application::SYSTEM_DEFAULT_MODULE . '\\Controller');
        $key = md5(__METHOD__);
        if(!($routes = $this->systemCache->start($key))) {
            $modules = $this->app->getModules();
            foreach ($modules as $name => $module) {
                // Get all file names.
                $files = glob($this->dir->app("{$name}/controllers/*.php"));
                // Iterate files.
                foreach ($files as $file) {
                    $controllerName = basename($file);
                    if(strpos($controllerName, 'Controller.php') === false) {
                        continue;
                    }
                    $controller = ucfirst($name) . '\\Controller\\' . str_replace('Controller.php', '', $controllerName);
                    $routes[$name][] = $controller;
                }
            }
            $this->systemCache->save($key, $routes);
        }
        foreach ($routes as $name => $controllers) {
            foreach ($controllers as $controller) {
                $router->addModuleResource($name, $controller);
            }
        }
        $this->di->setShared('router', $router);
        return $this;

    }

}